using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;

namespace fitnesstrack.library
{ 
	[Serializable()] 
	public class Exercise : Csla.BusinessBase<Exercise>
	{
		#region Business Properties and Methods

		//declare members
		private int _id = 0;
		private int _subCategoryID = 0;
		private string _name = string.Empty;

		[System.ComponentModel.DataObjectField(true, true)]
		public int Id
		{
			get
			{
				CanReadProperty("Id", true);
				return _id;
			}
		}

		public int SubCategoryID
		{
			get
			{
				CanReadProperty("SubCategoryID", true);
				return _subCategoryID;
			}
			set
			{
				CanWriteProperty("SubCategoryID", true);
				if (!_subCategoryID.Equals(value))
				{
					_subCategoryID = value;
					PropertyHasChanged("SubCategoryID");
				}
			}
		}

		public string Name
		{
			get
			{
				CanReadProperty("Name", true);
				return _name;
			}
			set
			{
				CanWriteProperty("Name", true);
				if (value == null) value = string.Empty;
				if (!_name.Equals(value))
				{
					_name = value;
					PropertyHasChanged("Name");
				}
			}
		}
 
		protected override object GetIdValue()
		{
			return _id;
		}

		#endregion //Business Properties and Methods

		#region Validation Rules
		private void AddCustomRules()
		{
			//add custom/non-generated rules here...
		}

		private void AddCommonRules()
		{
			//
			// Name
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "Name");
			ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Name", 255));
		}

		protected override void AddBusinessRules()
		{
			AddCommonRules();
			AddCustomRules();
		}
		#endregion //Validation Rules

		#region Authorization Rules
		protected override void AddAuthorizationRules()
		{
			//TODO: Define authorization rules in Exercise
			//AuthorizationRules.AllowRead("Id", "ExerciseReadGroup");
			//AuthorizationRules.AllowRead("SubCategoryID", "ExerciseReadGroup");
			//AuthorizationRules.AllowRead("Name", "ExerciseReadGroup");

			//AuthorizationRules.AllowWrite("SubCategoryID", "ExerciseWriteGroup");
			//AuthorizationRules.AllowWrite("Name", "ExerciseWriteGroup");
		}


		public static bool CanGetObject()
		{
			//TODO: Define CanGetObject permission in Exercise
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("ExerciseViewGroup"))
			//	return true;
			//return false;
		}

		public static bool CanAddObject()
		{
			//TODO: Define CanAddObject permission in Exercise
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("ExerciseAddGroup"))
			//	return true;
			//return false;
		}

		public static bool CanEditObject()
		{
			//TODO: Define CanEditObject permission in Exercise
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("ExerciseEditGroup"))
			//	return true;
			//return false;
		}

		public static bool CanDeleteObject()
		{
			//TODO: Define CanDeleteObject permission in Exercise
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("ExerciseDeleteGroup"))
			//	return true;
			//return false;
		}
		#endregion //Authorization Rules

		#region Factory Methods
		private Exercise()
		{ /* require use of factory method */ }

		public static Exercise NewExercise()
		{
			if (!CanAddObject())
				throw new System.Security.SecurityException("User not authorized to add a Exercise");
			return DataPortal.Create<Exercise>();
		}

		public static Exercise GetExercise(int id)
		{
			if (!CanGetObject())
				throw new System.Security.SecurityException("User not authorized to view a Exercise");
			return DataPortal.Fetch<Exercise>(new Criteria(id));
		}

		public static void DeleteExercise(int id)
		{
			if (!CanDeleteObject())
				throw new System.Security.SecurityException("User not authorized to remove a Exercise");
			DataPortal.Delete(new Criteria(id));
		}

		public override Exercise Save()
		{
			if (IsDeleted && !CanDeleteObject())
				throw new System.Security.SecurityException("User not authorized to remove a Exercise");
			else if (IsNew && !CanAddObject())
				throw new System.Security.SecurityException("User not authorized to add a Exercise");
			else if (!CanEditObject())
				throw new System.Security.SecurityException("User not authorized to update a Exercise");

			return base.Save();
		}

		#endregion //Factory Methods

		#region Data Access

		#region Criteria

		[Serializable()]
		private class Criteria
		{
			public int Id;

			public Criteria(int id)
			{
				this.Id = id;
			}
		}

		#endregion //Criteria

		#region Data Access - Create
		[RunLocal]
		protected override void DataPortal_Create()
		{
			ValidationRules.CheckRules();
		}

		#endregion //Data Access - Create

		#region Data Access - Fetch
		private void DataPortal_Fetch(Criteria criteria)
		{
			using (SqlConnection cn = new SqlConnection(Database.fitnesstrackConnection))
			{
				cn.Open();

				ExecuteFetch(cn, criteria);
			}//using
		}

		private void ExecuteFetch(SqlConnection cn, Criteria criteria)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "GetExercise";

				cm.Parameters.AddWithValue("@ID", criteria.Id);

				using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
				{
					FetchObject(dr);
					ValidationRules.CheckRules();

					//load child object(s)
					FetchChildren(dr);
				}
			}//using
		}

		private void FetchObject(SafeDataReader dr)
		{
			dr.Read();
			_id = dr.GetInt32("ID");
			_subCategoryID = dr.GetInt32("SubCategoryID");
			_name = dr.GetString("Name");
		}

		private void FetchChildren(SafeDataReader dr)
		{
		}
		#endregion //Data Access - Fetch

		#region Data Access - Insert
		protected override void DataPortal_Insert()
		{
			using (SqlConnection cn = new SqlConnection(Database.fitnesstrackConnection))
			{
				cn.Open();

				ExecuteInsert(cn);

				//update child object(s)
				UpdateChildren(cn);
			}//using

		}

		private void ExecuteInsert(SqlConnection cn)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "AddExercise";

				AddInsertParameters(cm);

				cm.ExecuteNonQuery();

				_id = (int)cm.Parameters["@NewID"].Value;
			}//using
		}

		private void AddInsertParameters(SqlCommand cm)
		{
			if (_subCategoryID != 0)
				cm.Parameters.AddWithValue("@SubCategoryID", _subCategoryID);
			else
				cm.Parameters.AddWithValue("@SubCategoryID", DBNull.Value);
			cm.Parameters.AddWithValue("@Name", _name);
			cm.Parameters.AddWithValue("@NewID", _id);
			cm.Parameters["@NewID"].Direction = ParameterDirection.Output;
		}
		#endregion //Data Access - Insert

		#region Data Access - Update
		protected override void DataPortal_Update()
		{
			using (SqlConnection cn = new SqlConnection(Database.fitnesstrackConnection))
			{
				cn.Open();

				if (base.IsDirty)
				{
					ExecuteUpdate(cn);
				}

				//update child object(s)
				UpdateChildren(cn);
			}//using

		}

		private void ExecuteUpdate(SqlConnection cn)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "UpdateExercise";

				AddUpdateParameters(cm);

				cm.ExecuteNonQuery();

			}//using
		}

		private void AddUpdateParameters(SqlCommand cm)
		{
			cm.Parameters.AddWithValue("@ID", _id);
			if (_subCategoryID != 0)
				cm.Parameters.AddWithValue("@SubCategoryID", _subCategoryID);
			else
				cm.Parameters.AddWithValue("@SubCategoryID", DBNull.Value);
			cm.Parameters.AddWithValue("@Name", _name);
		}

		private void UpdateChildren(SqlConnection cn)
		{
		}
		#endregion //Data Access - Update

		#region Data Access - Delete
		protected override void DataPortal_DeleteSelf()
		{
			DataPortal_Delete(new Criteria(_id));
		}

		private void DataPortal_Delete(Criteria criteria)
		{
			using (SqlConnection cn = new SqlConnection(Database.fitnesstrackConnection))
			{
				cn.Open();

				ExecuteDelete(cn, criteria);

			}//using

		}

		private void ExecuteDelete(SqlConnection cn, Criteria criteria)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "DeleteExercise";

				cm.Parameters.AddWithValue("@ID", criteria.Id);

				cm.ExecuteNonQuery();
			}//using
		}
		#endregion //Data Access - Delete
		#endregion //Data Access
	}
}
